package com.beyond.generate.utils;


import com.beyond.generate.entity.ColumnEntity;
import com.beyond.generate.entity.TableEntity;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.*;
import java.net.URL;
import java.util.*;

/**
 * 代码生成器   工具类
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017年1月3日 下午6:35:28
 */
public class GenUtils {

    /**
     * 获取目录模板
     *
     * @param configuration
     * @return
     */
    private static List<String> getTemplates(Configuration configuration) {
        List<String> templates = new ArrayList<>();
        String templateDir = configuration.getString("templateDir");
        String dir = StringUtils.isNotBlank(templateDir) ? "template/" + templateDir : "template/common";
        URL resource = GenUtils.class.getClassLoader().getResource(dir);
        File file = new File(resource.getPath());
        File[] files = file.listFiles();
        for (File templateFile : files) {
            String name = templateFile.getName();
            templates.add(dir + "/" + name);
        }
        return templates;
    }

    /**
     * 生成代码
     */
    public static void generatorCode(Map<String, String> table,
                                     List<Map<String, String>> columns) {
        //配置信息
        Configuration config = getConfig();
        //表信息
        TableEntity tableEntity = new TableEntity();
        tableEntity.setTableName(table.get("tableName"));
        tableEntity.setComments(table.get("tableComment"));
        String tablePrefix = table.get("tableName").split("_")[0];
        //表名转换成Java类名
        String className = tableToJava(tableEntity.getTableName(), tablePrefix);
        tableEntity.setClassName(className);
        tableEntity.setClassname(StringUtils.uncapitalize(className));

        //列信息
        List<ColumnEntity> columsList = new ArrayList<>();
        boolean hasDate = false;
        boolean hasBigDecimal = false;
        for (Map<String, String> column : columns) {
            ColumnEntity columnEntity = new ColumnEntity();
            columnEntity.setColumnName(column.get("columnName"));
            columnEntity.setDataType(column.get("dataType"));
            columnEntity.setComments(column.get("columnComment"));
            columnEntity.setExtra(column.get("extra"));

            //列名转换成Java属性名
            String attrName = columnToJava(columnEntity.getColumnName());
            columnEntity.setAttrName(attrName);
            columnEntity.setAttrname(StringUtils.uncapitalize(attrName));

            //列的数据类型，转换成Java类型
            String attrType = config.getString(columnEntity.getDataType().toLowerCase(), "String");
            columnEntity.setAttrType(attrType);

            if ("Date".equals(attrType)) {
                hasDate = true;
            }
            if ("BigDecimal".equals(attrType)) {
                hasBigDecimal = true;
            }
            //是否主键
            if ("ORACLE".equals(Constant.USE_DATA)) {
                if ((column.get("columnName").equalsIgnoreCase(column.get("columnKey")) && tableEntity.getPk() == null)) {
                    tableEntity.setPk(columnEntity);
                }
            } else {
                if (("PRI".equalsIgnoreCase(column.get("columnKey")) && tableEntity.getPk() == null)) {
                    tableEntity.setPk(columnEntity);
                }
            }

            columsList.add(columnEntity);
        }
        tableEntity.setColumns(columsList);
        //设置业务主键为表中第二个地段
        tableEntity.setPk(tableEntity.getColumns().get(1));
        String pre = tablePrefix.replace("_", "").toUpperCase();
        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
        //封装模板数据
        Map<String, Object> map = new HashMap<>();
        map.put("tableName", tableEntity.getTableName());
        map.put("comments", tableEntity.getComments());
        map.put("pk", tableEntity.getPk());
        map.put("className", tableEntity.getClassName());
        map.put("classname", tableEntity.getClassname());
        map.put("pathName", tableEntity.getClassname().toLowerCase());
        map.put("columns", tableEntity.getColumns());
        map.put("package", config.getString("package"));
        map.put("author", config.getString("author"));
        map.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        map.put("hasDate", hasDate);
        map.put("hasBigDecimal", hasBigDecimal);
        map.put("pre", pre);
        VelocityContext context = new VelocityContext(map);
        //获取模板列表
        List<String> templates = getTemplates(config);
        for (String template : templates) {
            //渲染模板
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            //写出
            writeFile(tpl, context, tableEntity, config, pre, template);
        }
    }

    /**
     * 列名转换成Java属性名
     */
    private static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }

    /**
     * 表名转换成Java类名
     */
    public static String tableToJava(String tableName, String tablePrefix) {
        if (StringUtils.isNotBlank(tablePrefix)) {
            tableName = tableName.replaceFirst(tablePrefix, "");
        }
        return columnToJava(tableName);
    }

    /**
     * 获取配置信息
     */
    private static Configuration getConfig() {
        try {
            return new PropertiesConfiguration("generator.properties");
        } catch (ConfigurationException e) {
            throw new RuntimeException("获取配置文件失败，", e);
        }
    }

    /**
     * 获取文件名
     */
    private static String getFileName(String template, String className, String packageName, String tablePrefix) {

//        String packagePath = "main" + File.separator + "java" + File.separator;
        String packagePath = "";
        String javaName = template.split(".vm")[0];
        String[] split = javaName.split("/");
        javaName = split[split.length - 1];
        if (StringUtils.isNotBlank(packageName)) {
            packagePath += packageName.replace(".", File.separator) + File.separator;
        }
        if (template.contains("PO.java")) {
            return packagePath + "po" + File.separator + className.toLowerCase() + File.separator + className + javaName;
        }
        if (template.contains("VO.java")) {
            return packagePath + "vo" + File.separator + className.toLowerCase() + File.separator + className + javaName;
        }

        if (template.contains("Query.java")) {
            return packagePath + "query" + File.separator + className.toLowerCase() + File.separator + className + javaName;
        }
        if (template.contains("ReqData.java")) {
            return packagePath + "reqdata" + File.separator + className.toLowerCase() + File.separator + className + javaName;
        }

        if (template.contains("Mapper.java")) {
            return packagePath + "mapper" + File.separator + className.toLowerCase() + File.separator + className + javaName;
        }

        if (template.contains("Mapper.xml")) {
            return packagePath + "mapper" + File.separator + className.toLowerCase() + File.separator + className + javaName;
        }

        if (template.contains("Manager.java")) {
            return packagePath + "manager" + File.separator + className.toLowerCase() + File.separator + className + javaName;
        }

        if (template.contains("ManagerImpl.java")) {
            return packagePath + "manager" + File.separator + className.toLowerCase() + File.separator + className + javaName;
        }

        if (template.contains("Controller")) {
            return packagePath + "controller" + File.separator + className.toLowerCase() + File.separator + className + javaName;
        }

        if (template.contains("ServiceApi")) {
            return packagePath + "service" + File.separator + className.toLowerCase() + File.separator + className + javaName;
        }
        if (template.contains("ServiceImpl")) {
            return packagePath + "service" + File.separator + className.toLowerCase() + File.separator + className + javaName;
        }

        return null;
    }

    private static void writeFile(Template template, VelocityContext context,
                                  TableEntity tableEntity, Configuration config, String pre, String templateStr) {
        try {
            String aPackage = getFileName(templateStr, tableEntity.getClassName(), config.getString("package"), pre);
            String path = config.getString("targetProject");
            File file = new File(path, aPackage);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream outStream = new FileOutputStream(file);
            OutputStreamWriter writer = new OutputStreamWriter(outStream,
                    "UTF-8");
            BufferedWriter sw = new BufferedWriter(writer);
            template.merge(context, sw);
            sw.flush();
            sw.close();
            outStream.close();
        } catch (Exception e) {
            e.getStackTrace();
        }

    }
}
